/**
 * 
 */
package cn.jhz.filesharingsystem.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import cn.jhz.filesharingsystem.model.Pager;
import cn.jhz.filesharingsystem.model.SharedFile;
import cn.jhz.filesharingsystem.model.SystemContext;
import cn.jhz.filesharingsystem.model.User;
import cn.jhz.filesharingsystem.service.SharedFileService;
import cn.jhz.filesharingsystem.util.HeadersUtil;
import cn.jhz.filesharingsystem.web.AuthClass;
import cn.jhz.filesharingsystem.web.AuthMethod;



/**
 * @author asus
 *
 */
@AuthClass
@Controller
public class FileSharingController {
	
	@Autowired
	SharedFileService sharedFileService;
	
	@AuthMethod
	@GetMapping("/file_management")
	private String usersManager(@RequestHeader(value="User-Agent") String userAgent) {
		if(HeadersUtil.checkAgentIsMobile(userAgent)) {
			return "mobileFileManagement";
		}
		return "fileManagement";
	}
	
	@AuthMethod
	@PostMapping(value = "/file")
	private @ResponseBody String addFile(@RequestParam(value = "file", required = true)MultipartFile file
			,@RequestParam(value = "notes", required = false)String notes
			,@RequestParam(value = "state", required = true)Integer state
			,@SessionAttribute(value = "loginUser")User loginUser
			,@SessionAttribute(value = "isadmin")boolean isadmin
			,HttpServletResponse resp) 
					 {
		try {

			if(loginUser.getRole().getState()==0 || loginUser.getState()==0) {
				throw new RuntimeException("帐号已被禁用");
			}
			
			if(!isadmin) {
				if(loginUser.getFiles().size()+1>loginUser.getRole().getfileCount()) {
					throw new RuntimeException("超出文件数量限制!");
				}
			}
			if(loginUser.getRole().getRoleName().equals("guest")) {
				state = 1;
			}
			//将传输放到service
			sharedFileService.saveFile(loginUser, state, notes, file);
			
		}catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "ok";
	}
	
	/**
	 * 删除多个文件
	 * @param ids
	 * @return
	 * @throws IOException
	 */
	@AuthMethod
	@DeleteMapping("/files")
	private @ResponseBody String deleteFiles(@SessionAttribute(value = "loginUser")User loginUser
			,@SessionAttribute(value = "isadmin")boolean isadmin
			,@RequestBody Integer...ids) throws IOException {
		try {
			SharedFile tempFile;
			if(!loginUser.getRole().getRoleName().equals("super")) {
				if(loginUser.getRole().getState()==0 || loginUser.getState()==0)
					throw new RuntimeException("帐号已被禁用");
			}
			
			for (Integer id : ids) {
				tempFile = sharedFileService.load(id);
				if(!(tempFile.getProvider().getId()==loginUser.getId())) 
					if(!isadmin) 
						if((!loginUser.getRole().getRoleName().equals("admin"))||tempFile.getState()==0)
							throw new RuntimeException("权限不足");
					
				sharedFileService.deleteRecord(tempFile);
			}		
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "ok";
	}

	
	@AuthMethod
	@PutMapping("/files")
	private @ResponseBody String updateFiles(@SessionAttribute(value = "loginUser")User loginUser
			, @RequestBody Integer...ids) throws IOException {
		try {
			if(loginUser.getRole().getState()==0 || loginUser.getState()==0) {
				throw new RuntimeException("帐号已被禁用");
			}
			if(loginUser.getRole().getRoleName().equals("guest")) {
				return "error";
			}
			for (Integer id : ids) {
				sharedFileService.updateState(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "ok";
	}

	/**
	 * 获取一个文件
	 * @param id
	 * @param req
	 * @return
	 * @throws IOException
	 */
	@AuthMethod
	@GetMapping("/file**")
	private void getFile(@RequestParam("id")Integer id
			,@SessionAttribute(value = "loginUser")User loginUser
			,HttpServletRequest req,HttpServletResponse resp) throws IOException {

		if(loginUser.getRole().getState()==0 || loginUser.getState()==0) {
			throw new RuntimeException("帐号已被禁用");
		}
		SharedFile file = sharedFileService.load(id);
		if(!(file.getState()>0)) {	
			if(!(loginUser.getEmail().equals(file.getProvider().getEmail()))) {
				if(!loginUser.getRole().getRoleName().equals("super")) {
					throw new RuntimeException("权限不足");
				}
			}
		}
		sharedFileService.download(file, req, resp);
	}
	

	
	/**
	  * 获取所有文件信息(分页)
	 * @param page
	 * @param rows
	 * @param filename
	 * @return
	 */
	@AuthMethod
	@GetMapping("/files_page**")
	private @ResponseBody Pager<SharedFile> getFilesPage(@RequestParam(value = "page", required = false)Integer page
			   ,@RequestParam(value = "rows", required = false) Integer rows
			   ,@RequestParam(value="filename",required=false) String filename
			   ,@SessionAttribute(value = "loginUser")User loginUser
			   ,@SessionAttribute(value = "isadmin")boolean isadmin) {
		
		if(page != null && page > 0) SystemContext.setPageOffset((page-1)*rows);
		if(rows != null && rows > 0) SystemContext.setPageSize(rows);
		
		Pager<SharedFile> pager = null;
		if(loginUser.getRole().getState()==0 || loginUser.getState()==0) {
			throw new RuntimeException("帐号已被禁用");
		}
		if(isadmin) {
			pager = sharedFileService.getAllPagerFile(filename, 0, true);
		}else if(loginUser.getRole().getRoleName().equals("admin")) {
			pager = sharedFileService.getAllPagerFile(filename, loginUser.getId(), true);
		}
		else {
			pager = sharedFileService.getAllPagerFile(filename,loginUser.getId(), false);	
		}
		
		SystemContext.removePageOffset();
		SystemContext.removePageSize();
		
		return pager;
	}
}




///**
//* 获取多个文件信息(列表)
//* @param model
//* @return
//*/
//@AuthMethod
//@GetMapping("/files_list")
//private String getFilesList(Model model) {
//	List<SharedFile> sharedFiles = sharedFileService.getAllFile();
//	model.addAttribute("files", sharedFiles);
//	return "filelist";
//}

///**
//* 上传多个文件
//* @param req
//* @param files
//* @return
//* @throws IllegalStateException
//* @throws IOException
//*/
//@PostMapping("/files")
//public String uploadMulti(String []notes,
//		@RequestParam("files")MultipartFile...files) throws IllegalStateException, IOException {
//	
//	try {
//		//将传输放到service
//		sharedFileService.saveFile(notes, files);
//	}catch (Exception e) {
//		return "error";
//	}
//	return "ok";	
//}

//
///**
//* 删除单个文件
//* @param id
//* @return
//* @throws IOException
//*/
//@AuthMethod
//@DeleteMapping("/file/{id}")
//private String deleteFile(@PathVariable("id")Integer id) throws IOException {
//	
//	try {
//		if(id!=null) 
//			sharedFileService.deleteRecord(id);
//	} catch (Exception e) {
//		e.printStackTrace();
//		return "error";
//	}
//	return "ok";
//}


///**
// * 获取一个文件
// * @param id
// * @param req
// * @return
// * @throws IOException
// */
//@AuthMethod
//@GetMapping("/file/{id}")
//private ResponseEntity<byte[]> getFile(
//		@PathVariable("id")Integer id, HttpServletRequest req) 
//				throws IOException {	
//	
//	/* 3.设置header */
//	HttpHeaders headers = new HttpHeaders();	
//	/* 设置content-disposition响应头控制浏览器以下载的方式打开文件 */
//	/*  MediaType.APPLICATION_OCTET_STREAM*/
//	//改用ajax方式下载application/x-msdownload
//	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//	
//	return new ResponseEntity<byte[]>(sharedFileService.download(id, headers),headers,HttpStatus.CREATED);
//}
